<template>
  <div>
    <div class="setting-container">
      <div class="app-container">
        <pagetools>
          <template #left>
            <span>共{{ total }}条数据</span>
          </template>
          <template #right>
            <el-button
              type="primary"
              @click="$router.push('/import?type=userpeoplebatch')"
              >excel导入</el-button
            >
            <el-button type="primary" size="small" @click="exportployesfn">
              excel导出
            </el-button>
            <el-button type="primary" size="small" @click="addployesfn">
              新增员工
            </el-button>
          </template>
        </pagetools>
        <el-card style="margin-top: 10px" v-loading="loading">
          <el-table :data="list" border>
            <el-table-column
              type="index"
              :index="indexfn"
              label="序号"
              sortable=""
            />
            <el-table-column prop="username" label="姓名" sortable="" />
            <el-table-column prop="username" label="姓名" sortable="">
              <template #default="{ row }">
                <img
                  @click="seecodefn(row.staffPhoto)"
                  v-imgerror="ddefaulturl"
                  :src="row.staffPhoto || ddefaulturl"
                  alt=""
                  class="staffphotoimg"
                />
              </template>
            </el-table-column>
            <el-table-column prop="mobile" label="手机号" sortable="" />
            <el-table-column prop="workNumber" label="工号" sortable="" />
            <el-table-column
              prop="formOfEmployment"
              :formatter="formatterfn"
              label="聘用形式"
              sortable=""
            />

            <el-table-column prop="departmentName" label="部门" sortable="" />
            <el-table-column prop="timeOfEntry" label="入职时间" sortable="">
              <template #default="{ row }">
                {{ row.timeOfEntry | timefilter('YYYY年MM月DD日') }}
              </template>
            </el-table-column>
            <el-table-column
              prop=""
              label="操作"
              sortable=""
              fixed="right"
              width="280"
            >
              <template #default="{ row }">
                <el-button
                  type="text"
                  size="small"
                  @click="$router.push(`/employees/detail/${row.id}`)"
                  >查看</el-button
                >
                <el-button type="text" size="small">转正</el-button>
                <el-button type="text" size="small">调岗</el-button>
                <el-button type="text" size="small">离职</el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="roleassinfn(row.id)"
                >
                  角色
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  :disabled="!btnrole('DELssss')"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <div style="height: 60px; margin-top: 10px">
            <!-- <el-pagination layout="prev, pager, next" /> -->
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-sizes="[3, 5, 10, 20]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
            >
            </el-pagination>
            <el-dialog
              title="个人信息二维码"
              :visible.sync="showdialog"
              width="30%"
            >
              <div style="text-align: center">
                <canvas id="canvas"></canvas>
              </div>
              <!-- <span>这是一段信息</span>
              <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogVisible = false"
                  >确 定</el-button
                > -->
              <!-- </span> -->
            </el-dialog>
          </div>
        </el-card>
        <addemPloyesVue :showDialog.sync="showDialog"></addemPloyesVue>
        <!-- 分配角色碳层 -->
        <assginroleVue
          :showroledialog.sync="showroledialog"
          :userid="userid"
        ></assginroleVue>
      </div>
    </div>
  </div>
</template>

<script>
import { getuserlistapi } from '@/api/employes'
import employesobj from '@/constant/employees'
import { timefilter } from '@/fiflter'
import addemPloyesVue from './componments/addemPloyes.vue'
import defaultimg from '@/assets/common/bigUserHeader.png'
import qrcode from 'qrcode'
import btnrole from '@/mixins/btnrole'
import assginroleVue from './componments/assginrole.vue'
export default {
  components: {
    addemPloyesVue,
    assginroleVue
  },
  mixins: [btnrole],
  async created() {
    // console.log(this.$store.getters.poins)
    this.getuserlistfn()
  },
  data() {
    return {
      list: [], // 员工列表
      total: 0, // 数据总数
      // currentPage1: 1,
      page: 1,
      pagesize: 10,
      loading: false,
      showDialog: false, // 添加员工的显示状态
      ddefaulturl: defaultimg,
      showdialog: false,
      showroledialog: false,
      userid: '' // 员工id
    }
  },
  methods: {
    // 分配角色
    roleassinfn(id) {
      this.showroledialog = true
      this.userid = id
    },
    async getuserlistfn() {
      this.loading = true
      const { data } = await getuserlistapi(this.page, this.pagesize)
      this.list = data.rows
      this.total = data.total
      this.loading = false
    },
    // 每页条数变化，切换每页条数
    handleSizeChange(val) {
      this.pagesize = val
      this.page = 1
      this.getuserlistfn()
      console.log(`每页 ${val} 条`)
    },
    // 改变当前页执行
    handleCurrentChange(val) {
      this.page = val

      this.getuserlistfn()
      console.log(`当前页: ${val}`)
    },
    indexfn(index) {
      return index + 1 + (this.page - 1) * this.pagesize
    },
    // 格式化内容
    formatterfn(row, column, cellValue, index) {
      // row,一行数据
      // column,当前列的信息
      // cellValue,当前列的值
      // index,索引
      const { hireType } = employesobj
      const result = hireType.find((item) => item.id === +cellValue)
      return result ? result.value : '未知'
      // if (cellValue === 1 || cellValue === '1') {
      //   return '正式'
      // } else if (cellValue === 2 || cellValue === '2') {
      //   return '非正式'
      // }
    },
    // 打开碳层
    addployesfn() {
      this.showDialog = true
    },
    // 导出excel
    async exportployesfn() {
      const { data } = await getuserlistapi(this.page, this.total)
      const row = data.rows
      // console.log(row)
      import('@/vendor/Export2Excel').then((excel) => {
        // 表头
        const tHeader = [
          '姓名',
          '手机号',
          '工号',
          '聘用形式',
          '部门',
          '入职时间'
        ]
        const headersRelations = {
          姓名: 'username',
          手机号: 'mobile',
          入职时间: 'timeOfEntry',
          聘用形式: 'formOfEmployment',
          转正日期: 'correctionTime',
          工号: 'workNumber',
          部门: 'departmentName'
        }
        const multiHeader = [['姓名', '主演信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:E1', 'G1:G2']
        // // 定义每一行的数据
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = [{ id: '123', title: '456' }]
        const data = this.formatJson(row, tHeader, headersRelations)
        // console.log(data)
        excel.export_json_to_excel({
          header: tHeader,
          // data: [['khdjkh', '54564564', 'jdhsgjk']], // 二维数组
          data,
          filename: '员工统计表', // 导出文件名
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx', // 导出类型
          multiHeader: multiHeader, // 配置多表头
          merges: merges // 合并单元格
        })
        // this.downloadLoading = false
      })
    },
    formatJson(row, tHeader, headersRelations) {
      //   row决定了行数
      //   theader决定了行数
      const arr = []
      row.forEach((item) => {
        // itemarr每一行的数据
        const itemarr = []
        tHeader.forEach((itemm) => {
          // it每一列数据
          const englishkey = headersRelations[itemm]
          let val = item[englishkey]
          // 对聘用形式进行加工
          if (englishkey === 'formOfEmployment') {
            const { hireType } = employesobj
            const result = hireType.find((item) => item.id === Number(val))
            val = result ? result.value : '未知'
          }
          // // 对时间进行转换
          // if (englishkey === 'timeOfEntry' || englishkey === 'correctionTime') {
          //   val = timefilter(val, 'YYYY年MM月DD日')
          // }
          if (['timeOfEntry', 'correctionTime'].includes(englishkey)) {
            val = timefilter(val, 'YYYY年MM月DD日')
          }

          itemarr.push(val)
        })
        arr.push(itemarr)
      })
      return arr
    },

    seecodefn(url) {
      this.showdialog = true

      // 参数一:制定二维码渲染的元素
      // 参数二：转化生成二维码的内容
      this.$nextTick(() => {
        var canvas = document.getElementById('canvas')
        qrcode.toCanvas(canvas, url, function (error) {
          if (error) console.error(error)
          console.log('success!')
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.staffphotoimg {
  width: 70px;
  height: 70px;
  border-radius: 50%;
}
</style>
